<template>
  <el-upload
    class="avatar-uploader"
    :action="config.action"
    :data="data.uploadKey"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="data.image" :src="data.image" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import { reactive, onMounted, watch } from "@vue/composition-api";
import { getQiniuToken } from "../../api/article";
export default {
  props: {
    imgUrl: {
      type: String,
      default: ""
    },
    config: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props, { root, emit }) {
    console.log(props.imgUrl);
    const data = reactive({
      uploadKey: {
        token: "",
        key: ""
      },
      image: ""
    });

    const handleAvatarSuccess = (res, file) => {
      // form.imgUrl = URL.createObjectURL(file.raw);
      const imgSrc = `http://www-wb-jshtml-cn-idva7mx.web-jshtml.cm/${
        res.key /** ←上传成功返回的*/
      }`;
      data.image = imgSrc;
      emit("update:imgUrl", imgSrc);
    };
    const beforeAvatarUpload = file => {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        root.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        root.$message.error("上传头像图片大小不能超过 2MB!");
      }

      // 文件名转码
      const suffix = file.name;
      const key = encodeURI(`${suffix}`);
      data.uploadKey.key = key;

      return isJPG && isLt2M;
    };
    const x = () => {
      const requestData = {
        bucket: props.bucket
      };
      getQiniuToken(requestData).then(res => {
        console.log(res);
        data.uploadKey.token = res.token;
        console.log();
      });
    };

    onMounted(() => {
      x();
    });

    watch(
      () => props.imgUrl,
      value => {
        console.log(value);
        data.image = value;
      }
    );

    return {
      handleAvatarSuccess,
      beforeAvatarUpload,
      data
    };
  }
};
</script>

<style lang="scss" scoped></style>
